import { COMMON_REDUCER } from './dvaEffectsEnhancer'

/** 不定形参辅助函数 */
export const argumentHelp = paramArr => {
  const ret = {}
  paramArr.forEach(item => {
    const type = typeof item
    if (['number', 'boolean', 'string', 'function'].includes(type)) {
      ret[type] = item
    } else if (type === 'object') {
      if (Array.isArray(item)) {
        ret.array = item
      } else if (item) {
        ret.object = item
      }
    }
  })
  return ret
}

/** 获取基础函数 */
export const getBasicFn = config => {
  const { namespace, loading: { effects = {} } = {} } = config

  if (!namespace) {
    throw new Error('getBasicFn初始化必须传入namespace')
  }

  const prefix = `${namespace}/`

  const toAction = (...props) => {
    const { object: payload, string: type = COMMON_REDUCER, boolean: partObj = false } = argumentHelp(props)
    return window.dvaApp._store.dispatch({
      type: type.includes('/') ? type : `${prefix}${type}`,
      payload,
      partObj,
    })
  }

  const getLoading = (...arr) => arr.some(item => effects[`${prefix}${item}`])

  return {
    getLoading,
    toAction,
  }
}

/**
 * 根据namespace获取state
 * @param {string} namespace
 * @returns
 */
export const getState = namespace => {
  const { [namespace]: state } = window.dvaApp._store.getState()
  return state
}

/**
 * 获取namespace为app的state
 * @returns {import('@/models/app').state}
 */
export const getAppState = () => {
  return getState('app')
}
